package com.example.demo.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Json序列化组建
 * 用于处理LocalDateTime类型的转换
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@JsonComponent
public class DateTimeFormatterConfiguration {

    @Value("${spring.jackson.data-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * 初始化 LocalDateTime 序列化器
     *
     * @return LocalDateTime 序列化器
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 初始化 LocalDateTime 反序列化器
     *
     * @return LocalDateTime 反序列化器
     */
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(
            LocalDateTimeSerializer localDateTimeSerializer,
            LocalDateTimeDeserializer localDateTimeDeserializer) {

        return builder -> {
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer);
            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer);
            builder.simpleDateFormat(pattern);
        };
    }
}
